﻿using System;
using System.Collections.Concurrent;
using System.Net;
using Grundy.Common;
using Grundy.Entity;
using Grundy.Licensing.Server.Command;
using Grundy.Message;

namespace Grundy.Licensing.Server
{
    public class ExecutionCountConcurrentSessionsStrategy : CountedConcurrentSessionsStrategy
    {
        private readonly ExecutionCounter _executionCounter;

        public ExecutionCountConcurrentSessionsStrategy(ExecutionCounter executionCounter, License license, LicenseEntitlementValidity licenseEntitlementValidity, FeatureIdentificationKey featureIdentificationKey) : base(license, licenseEntitlementValidity, featureIdentificationKey)
        {
            _executionCounter = executionCounter;
        }

        protected override Guid CheckoutLicense(LicenseRequestInformation lri, object syncLock)
        {
            var license = (CountedFloatingLicense)License;

            var result = _executionCounter.CheckAndIncrement(FeatureIdentificationKey, license.Limit, lri);
            if (!result.Item1)
                throw new CountedFloatingLicensesExhaustedException(FeatureIdentificationKey, license, result.Item2);
            return Guid.NewGuid();
        }

        public override long GetExhaustedLicenseCount()
        {
            return _executionCounter.GetExecutionCount(FeatureIdentificationKey).Executions;
        }

        protected override Guid VerifyValidityAndCheckout(ConcurrentDictionary<Guid, ClientSession> clientSessions, LicenseRequestInformation lri, IdentifierCollection clientIdentifiersToUse)
        {
            throw new NotImplementedException();
        }

        public override bool Checkin(LicenseRequestInformation lri, object syncLock)
        {
            return true;
        }

        public override bool Reassert(Guid clientSessionId, EndPoint endpoint)
        {
            return true;
        }

    }
}